package rpc

import (
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	"gitee.com/zaiqiang231/lovesport-user-service/app/rpc/proto"
	"google.golang.org/grpc"
	"log"
	"sync"
)

var (
	userRpc   *UserRpc
	onceCache sync.Once
)

func GetUserRpc() *UserRpc {
	if userRpc == nil {
		baseLog.Errorf("userRpc instance is %v", userRpc)
	}
	return userRpc
}

type UserRpc struct {
	lock                         *sync.RWMutex
	UserRpcServiceClient         proto.UserRpcServiceClient
	UserPoliciesRpcServiceClient proto.UserPoliciesRpcServiceClient
}

func InitRpc(rpcAddr string) (*UserRpc, error) {
	onceCache.Do(func() {
		conn, err := grpc.Dial(rpcAddr, grpc.WithInsecure())
		if err != nil {
			log.Fatalf("rpc did not connect: %v", err)
		}
		userRpc = &UserRpc{
			UserRpcServiceClient:         proto.NewUserRpcServiceClient(conn),
			UserPoliciesRpcServiceClient: proto.NewUserPoliciesRpcServiceClient(conn),
		}
	})
	return userRpc, nil
}
